// ==UserScript==
// @name         新奥安全考试答案助手
// @namespace    http://tampermonkey.net/
// @version      2.0
// @description  简洁的题目答案显示工具
// @author       Assistant
// @match        https://xuexi.enn.cn/*
// @grant        none
// ==/UserScript==

(function() {
    'use strict';
    
    // 目标API URL匹配
    const targetUrls = [
        'safetraining/api/user/selectTestPaperInfo',
        'selectTestPaperInfo',
        '/api/user/selectTestPaperInfo'
    ];
    
    const isTargetUrl = (url) => {
        return targetUrls.some(targetUrl => url.includes(targetUrl));
    };
    
    let currentAnswers = []; // 当前答案数据
    
    // 创建贴边隐藏的悬浮球
    const createFloatingBall = () => {
        const ball = document.createElement('div');
        ball.id = 'answer-ball';
        ball.style.cssText = `
            position: fixed;
            top: 50%;
            right: 0;
            width: 50px;
            height: 50px;
            background: linear-gradient(45deg, #4CAF50, #45a049);
            border-radius: 25px 0 0 25px;
            cursor: pointer;
            z-index: 10001;
            display: flex;
            align-items: center;
            justify-content: center;
            color: white;
            font-size: 18px;
            box-shadow: -2px 2px 10px rgba(0,0,0,0.3);
            transition: all 0.3s ease;
            transform: translateX(35px);
        `;
        ball.innerHTML = '📝';
        ball.title = '等待题目加载...';
        
        // 鼠标悬停效果
        ball.onmouseenter = () => {
            ball.style.transform = 'translateX(0)';
        };
        ball.onmouseleave = () => {
            ball.style.transform = 'translateX(35px)';
        };
        
        // 点击显示答案
        ball.onclick = () => {
            if (currentAnswers.length > 0) {
                showAnswerPopup();
            }
        };
        
        // 双击隐藏球
        ball.ondblclick = () => {
            ball.style.display = 'none';
            setTimeout(() => {
                ball.style.display = 'flex';
            }, 3000);
        };
        
        document.body.appendChild(ball);
        return ball;
    };
    
    // 创建答案弹窗
    const showAnswerPopup = () => {
        // 移除已存在的弹窗
        const existingPopup = document.getElementById('answer-popup');
        if (existingPopup) {
            existingPopup.remove();
        }
        
        const popup = document.createElement('div');
        popup.id = 'answer-popup';
        popup.style.cssText = `
            position: fixed;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            width: 320px;
            max-height: 70vh;
            background: white;
            border-radius: 8px;
            box-shadow: 0 4px 20px rgba(0,0,0,0.3);
            z-index: 10002;
            overflow: hidden;
            font-family: 'Microsoft YaHei', Arial, sans-serif;
        `;
        
        // 标题栏
        const header = document.createElement('div');
        header.style.cssText = `
            background: #4CAF50;
            color: white;
            padding: 12px 15px;
            font-size: 16px;
            font-weight: bold;
            display: flex;
            justify-content: space-between;
            align-items: center;
        `;
        header.innerHTML = `
            <span>📝 题目答案</span>
            <span style="cursor: pointer; font-size: 20px; line-height: 1;" onclick="this.closest('#answer-popup').remove()">×</span>
        `;
        
        // 内容区域
        const content = document.createElement('div');
        content.style.cssText = `
            padding: 15px;
            max-height: calc(70vh - 60px);
            overflow-y: auto;
            color: #333;
        `;
        
        // 添加答案内容
        currentAnswers.forEach((item, index) => {
            const answerDiv = document.createElement('div');
            answerDiv.style.cssText = `
                margin-bottom: 12px;
                padding: 10px;
                background: #f5f5f5;
                border-radius: 6px;
                border-left: 4px solid #4CAF50;
            `;
            
            const answerText = item.optionsList.find(opt => opt.value === item.answer)?.name || '';
            
            answerDiv.innerHTML = `
                <div style="font-weight: bold; color: #4CAF50; margin-bottom: 5px;">第${index + 1}题</div>
                <div style="font-size: 14px; color: #666; margin-bottom: 8px;">${item.title}</div>
                <div style="background: #4CAF50; color: white; padding: 6px 10px; border-radius: 4px; font-size: 14px; font-weight: bold;">
                    ${item.answer}. ${answerText}
                </div>
            `;
            
            content.appendChild(answerDiv);
        });
        
        popup.appendChild(header);
        popup.appendChild(content);
        document.body.appendChild(popup);
        
        // 点击外部关闭
        const overlay = document.createElement('div');
        overlay.style.cssText = `
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0,0,0,0.5);
            z-index: 10001;
        `;
        overlay.onclick = () => {
            popup.remove();
            overlay.remove();
        };
        document.body.insertBefore(overlay, popup);
    };
    
    // 处理答案数据
    const processAnswers = (data) => {
        let topicList = [];
        if (data && data.courseTopicList && data.courseTopicList.length > 0) {
            topicList = data.courseTopicList;
        } else if (data && data.topicItemList && data.topicItemList.length > 0) {
            topicList = data.topicItemList;
        }
        
        if (topicList.length > 0) {
            currentAnswers = topicList;
            updateFloatingBall();
        }
    };
    
    // 更新悬浮球状态
    const updateFloatingBall = () => {
        const ball = document.getElementById('answer-ball');
        if (ball && currentAnswers.length > 0) {
            ball.style.background = 'linear-gradient(45deg, #FF5722, #F44336)';
            ball.innerHTML = '🎯';
            ball.title = `点击显示答案 (${currentAnswers.length}题)`;
            
            // 闪烁提示动画
            ball.style.animation = 'pulse 2s infinite';
            const style = document.createElement('style');
            style.textContent = `
                @keyframes pulse {
                    0% { box-shadow: -2px 2px 10px rgba(0,0,0,0.3); }
                    50% { box-shadow: -2px 2px 20px rgba(255,87,34,0.6); }
                    100% { box-shadow: -2px 2px 10px rgba(0,0,0,0.3); }
                }
            `;
            document.head.appendChild(style);
        }
    };
    
    // 拦截 XMLHttpRequest
    const originalXHR = window.XMLHttpRequest;
    window.XMLHttpRequest = function() {
        const xhr = new originalXHR();
        const originalOpen = xhr.open;
        const originalSend = xhr.send;
        
        let requestUrl = '';
        
        xhr.open = function(method, url) {
            requestUrl = url;
            return originalOpen.apply(this, arguments);
        };
        
        xhr.send = function(data) {
            xhr.addEventListener('load', function() {
                if (requestUrl && isTargetUrl(requestUrl) && xhr.status === 200) {
                    try {
                        const responseData = JSON.parse(xhr.responseText);
                        if (responseData.code === 200 && responseData.data) {
                            processAnswers(responseData.data);
                        }
                    } catch (e) {
                        // 静默处理错误
                    }
                }
            });
            
            return originalSend.apply(this, arguments);
        };
        
        return xhr;
    };
    
    // 拦截 fetch
    const originalFetch = window.fetch;
    window.fetch = function() {
        return originalFetch.apply(this, arguments).then(response => {
            if (response.url && isTargetUrl(response.url) && response.status === 200) {
                const clonedResponse = response.clone();
                clonedResponse.json().then(data => {
                    if (data.code === 200 && data.data) {
                        processAnswers(data.data);
                    }
                }).catch(() => {
                    // 静默处理错误
                });
            }
            return response;
        });
    };
    
    // 初始化脚本
    const init = () => {
        createFloatingBall();
    };

    // 页面加载完成后初始化
    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', init);
    } else {
        init();
    }
    
})();
